import {
  Routes,
  Route,
  Link,
  useLocation,
  Navigate,
  useNavigate,
} from "react-router-dom";
import Home from "./pages/Home";
import About from "./pages/About";
import Users from "./pages/Users";
import Articles from "./pages/Articles";
import Profile from "./pages/Profile";
import Category from "./pages/Category";
import UserChat from "./pages/UserChat";
import {
  Layout,
  Menu,
  Button,
  message,
  Modal,
  Avatar,
  Drawer,
  Input,
  List,
  Typography,
  Space,
  Spin,
  ConfigProvider,
  theme,
  Switch,
  Select,
  Tooltip,
} from "antd";
import React, { useState, useEffect, useRef } from "react";
import Logs from "./pages/Logs";
import Stats from "./pages/Stats";
import ArticleDetail from "./pages/ArticleDetail";
import Login from "./pages/Login";
import Register from "./pages/Register";
import Comments from "./pages/Comments";
import ApiLogs from "./pages/ApiLogs";
import { logout, getUserProfile } from "./api/users";
import { sendChatMessage, sendChatMessageStream } from "./api/chat";
import { joinQueue, leaveQueue } from "./api/userChat";
import { getAiHistory, deleteAiHistory } from "./api/aiHistory";
import ChatMessage from "./components/ChatMessage";
import { clearUserRole, isAdmin } from "./utils/auth";
import { ThemeProvider, useTheme } from "./contexts/ThemeContext";
import {
  UserOutlined,
  MessageOutlined,
  SendOutlined,
  RobotOutlined,
  SunOutlined,
  MoonOutlined,
  TeamOutlined,
  SettingOutlined,
  SwapOutlined,
  ClearOutlined,
  HomeOutlined,
  InfoCircleOutlined,
  AppstoreOutlined,
  FileTextOutlined,
  TagsOutlined,
  CommentOutlined,
  FileSearchOutlined,
  ApiOutlined,
  BarChartOutlined,
  DeleteOutlined,
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons";

import { setupGlobalErrorHandler } from "./utils/globalErrorHandler";
setupGlobalErrorHandler();

const { Sider, Content } = Layout;
const { TextArea } = Input;
const { Text } = Typography;

export default function App() {
  // 添加全局滚动条样式
  useEffect(() => {
    const style = document.createElement("style");
    style.innerHTML = `
      /* 自定义滚动条样式 - Webkit浏览器 */
      .menu-scroll-container::-webkit-scrollbar {
        width: 8px;
        display: block !important; /* 强制显示滚动条 */
      }
      
      .menu-scroll-container::-webkit-scrollbar-track {
        background: #f0f0f0;
        border-radius: 4px;
      }
      
      .menu-scroll-container::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
      }
      
      .menu-scroll-container::-webkit-scrollbar-thumb:hover {
        background: #555;
      }
      
      /* 深色模式滚动条 */
      .dark-mode .menu-scroll-container::-webkit-scrollbar-track {
        background: #2a2a2a;
      }
      
      .dark-mode .menu-scroll-container::-webkit-scrollbar-thumb {
        background: #434343;
      }
      
      .dark-mode .menu-scroll-container::-webkit-scrollbar-thumb:hover {
        background: #595959;
      }
      
      /* 需要时显示滚动条 */
      .menu-scroll-container {
        overflow-y: auto !important;
      }
    `;
    document.head.appendChild(style);

    return () => {
      document.head.removeChild(style);
    };
  }, []);

  return (
    <ThemeProvider>
      <AppContent />
    </ThemeProvider>
  );
}

function AppContent() {
  const { isDarkMode, toggleDarkMode } = useTheme();

  // 修复全局滚动条失效问题
  useEffect(() => {
    // 恢复body和html的overflow为auto，防止被覆盖
    document.body.style.overflow = "auto";
    document.documentElement.style.overflow = "auto";
    return () => {
      document.body.style.overflow = "";
      document.documentElement.style.overflow = "";
    };
  }, []);
  const location = useLocation();
  const navigate = useNavigate();
  const [hasToken, setHasToken] = useState(false);
  const [isCheckingToken, setIsCheckingToken] = useState(true);
  const [siderWidth, setSiderWidth] = useState(200);
  const [hasJoinedQueue, setHasJoinedQueue] = useState(false); // 新增：是否已加入队列的标记
  const [siderCollapsed, setSiderCollapsed] = useState(false); // 侧边栏是否折叠
  const [isMobile, setIsMobile] = useState(false); // 是否为移动端

  // 聊天助手相关状态
  // 用户头像相关
  const [userImg, setUserImg] = useState(null);
  // 获取头像
  useEffect(() => {
    async function fetchImg() {
      const userId = localStorage.getItem("userId");
      if (!userId) return;
      try {
        const res = await getUserProfile(userId);
        if ((res.code === 1 || res.code === 200) && res.data) {
          setUserImg(res.data.img || null);
        }
      } catch {}
    }
    if (hasToken) fetchImg();
  }, [hasToken]);

  // 加载聊天历史记录
  useEffect(() => {
    if (hasToken && !isLoadingHistory) {
      loadChatHistory();
    }
  }, [hasToken]);
  const [chatVisible, setChatVisible] = useState(false);
  const [chatMessages, setChatMessages] = useState([]);
  const [currentMessage, setCurrentMessage] = useState("");
  const [chatLoading, setChatLoading] = useState(false);
  const [chatService, setChatService] = useState("gemini"); // 新增:AI服务选择
  const [conversationId] = useState("user_" + Date.now()); // 生成唯一会话ID
  const [isLoadingHistory, setIsLoadingHistory] = useState(false); // 是否正在加载历史记录
  const chatMessagesEndRef = useRef(null);

  // 处理服务切换
  const handleServiceChange = (newService) => {
    if (newService !== chatService) {
      setChatService(newService);
      // 切换服务时保留聊天记录，不再清空
      const serviceName =
        newService === "gemini"
          ? "Gemini"
          : newService === "doubao"
          ? "豆包"
          : "通义千问";
      console.log(`已切换到 ${serviceName} 服务，历史记录已保留`);
    }
  };

  // 清除聊天记录
  const handleClearChat = async () => {
    const userId = localStorage.getItem("userId");
    if (!userId) {
      message.warning("用户信息不存在");
      return;
    }

    try {
      // 调用后端API删除用户的所有聊天历史记录
      await deleteAiHistory(parseInt(userId));
      // 清空前端显示的聊天记录
      setChatMessages([]);
      message.success("聊天记录已清除");
    } catch (error) {
      console.error("删除聊天记录失败:", error);
      message.error("删除聊天记录失败，请重试");
    }
  };

  // 加载AI聊天历史记录
  const loadChatHistory = async () => {
    const userId = localStorage.getItem("userId");
    if (!userId) return;

    setIsLoadingHistory(true);
    try {
      const response = await getAiHistory(userId);
      if (
        response.code === 1 &&
        response.data &&
        Array.isArray(response.data)
      ) {
        // 转换后端数据格式为前端聊天消息格式
        const historyMessages = [];
        response.data.forEach((record) => {
          // 用户消息
          historyMessages.push({
            id: `user_${record.id}_${record.created_at}`,
            type: "user",
            content: record.ask,
            timestamp: new Date(record.created_at),
          });
          // AI回复
          historyMessages.push({
            id: `ai_${record.id}_${record.created_at}`,
            type: "ai",
            content: record.reply,
            timestamp: new Date(record.created_at),
            service: record.ai_type, // gemini 或 coze
            isStreaming: false,
          });
        });
        setChatMessages(historyMessages);
        console.log(`成功加载${response.data.length}条聊天历史记录`);
      }
    } catch (error) {
      console.error("加载聊天历史失败:", error);
      // 不显示错误提示,避免干扰用户
    } finally {
      setIsLoadingHistory(false);
    }
  };

  // 自动滚动到聊天消息底部
  const scrollToBottom = () => {
    chatMessagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [chatMessages]);

  // 当聊天窗口打开时滚到底部
  useEffect(() => {
    if (chatVisible) {
      setTimeout(() => {
        scrollToBottom();
      }, 100);
    }
  }, [chatVisible]);

  const selectedKey = location.pathname === "/" ? "/" : location.pathname;
  // 判断是否为登录页或注册页
  const isLoginPage = location.pathname === "/login";
  const isRegisterPage = location.pathname === "/register";

  // 响应式调整侧边栏宽度和移动端检测
  useEffect(() => {
    const handleResize = () => {
      const screenWidth = window.innerWidth;
      const screenHeight = window.innerHeight;
      const isPortrait = screenHeight > screenWidth; // 竖屏检测

      // 移动端检测：宽度小于768px 或 竖屏模式
      const mobile = screenWidth < 768 || isPortrait;
      setIsMobile(mobile);

      if (mobile) {
        // 移动端：自动折叠侧边栏
        setSiderCollapsed(true);
        setSiderWidth(0);
      } else {
        // PC端：根据屏幕宽度调整侧边栏
        setSiderCollapsed(false);
        if (screenWidth < 1200) {
          setSiderWidth(180);
        } else {
          setSiderWidth(200);
        }
      }
    };

    handleResize(); // 初始调用
    window.addEventListener("resize", handleResize);
    // 监听屏幕方向变化
    window.addEventListener("orientationchange", handleResize);
    return () => {
      window.removeEventListener("resize", handleResize);
      window.removeEventListener("orientationchange", handleResize);
    };
  }, []);

  // 检查JWT令牌的函数
  const checkToken = () => {
    const token = localStorage.getItem("token");
    return !!token;
  }; // 在组件挂载时检查token
  useEffect(() => {
    const tokenExists = checkToken();
    setHasToken(tokenExists);
    setIsCheckingToken(false);

    // 检查是否刚刚登录成功
    const justLoggedIn = localStorage.getItem("justLoggedIn");
    if (justLoggedIn === "true") {
      // 立即清除标记，防止重复显示
      localStorage.removeItem("justLoggedIn");

      // 延迟一点显示弹窗，确保页面完全加载
      setTimeout(() => {
        Modal.success({
          title: "登录成功",
          content: "欢迎回来！",
          centered: true,
        });
      }, 500);
    }

    // 如果已登录，自动加入聊天队列
    if (tokenExists && !hasJoinedQueue) {
      autoJoinChatQueue();
    }
  }, [hasJoinedQueue]);

  // 自动加入聊天队列
  const autoJoinChatQueue = async () => {
    // 避免重复加入
    if (hasJoinedQueue) {
      return;
    }

    const userId = localStorage.getItem("userId");
    const username = localStorage.getItem("username");

    if (userId && username) {
      try {
        await joinQueue({
          userId: userId,
          username: username,
        });
        setHasJoinedQueue(true);
        console.log("自动加入聊天队列成功");
      } catch (error) {
        console.error("自动加入聊天队列失败:", error);
        // 不显示错误提示，避免干扰用户体验
      }
    }
  };

  // 自动离开聊天队列
  const autoLeaveChatQueue = async (userId) => {
    // 只有已加入队列才需要离开
    if (!hasJoinedQueue) {
      return;
    }

    if (userId) {
      try {
        await leaveQueue({
          userId: userId,
        });
        setHasJoinedQueue(false);
        console.log("自动离开聊天队列成功");
      } catch (error) {
        console.error("自动离开聊天队列失败:", error);
        // 不显示错误提示
      }
    }
  };

  // 监听路由变化，重新检查token状态
  useEffect(() => {
    const tokenExists = checkToken();
    const wasLoggedIn = hasToken;
    setHasToken(tokenExists);

    // 如果从未登录变为已登录，自动加入聊天队列
    if (!wasLoggedIn && tokenExists && !hasJoinedQueue) {
      autoJoinChatQueue();
    }
    // 如果从已登录变为未登录，自动离开聊天队列
    else if (wasLoggedIn && !tokenExists && hasJoinedQueue) {
      const userId = localStorage.getItem("userId");
      autoLeaveChatQueue(userId);
    }
  }, [location.pathname, hasToken, hasJoinedQueue]);

  // 添加一个定时器来检查token状态变化（处理登录后的状态更新）
  useEffect(() => {
    const interval = setInterval(() => {
      const tokenExists = checkToken();
      if (tokenExists !== hasToken) {
        setHasToken(tokenExists);
      }
    }, 200); // 每200ms检查一次

    return () => clearInterval(interval);
  }, [hasToken]);

  // 获取userId
  function getUserId() {
    return localStorage.getItem("userId");
  }

  // 登出处理
  const handleLogout = async () => {
    const userId = getUserId();

    // 先离开聊天队列
    if (userId && hasJoinedQueue) {
      await autoLeaveChatQueue(userId);
    }

    if (!userId) {
      localStorage.removeItem("token");
      localStorage.removeItem("userId");
      localStorage.removeItem("username");
      clearUserRole(); // 清除用户角色
      setHasToken(false);
      setHasJoinedQueue(false);
      navigate("/login");
      return;
    }
    try {
      await logout(userId);
    } catch (e) {
      // 忽略接口异常
    }
    localStorage.removeItem("token");
    localStorage.removeItem("userId");
    localStorage.removeItem("username");
    clearUserRole(); // 清除用户角色
    setHasToken(false);
    setHasJoinedQueue(false);
    message.success("已登出");
    navigate("/login");
  };

  // 发送聊天消息
  const handleSendMessage = async () => {
    if (!currentMessage.trim()) {
      message.warning("请输入消息内容");
      return;
    }

    // 添加用户消息到聊天记录
    const userMessage = {
      id: "user_" + Date.now(),
      type: "user",
      content: currentMessage,
      timestamp: new Date(),
    };

    setChatMessages((prev) => [...prev, userMessage]);
    const messageToSend = currentMessage;
    setCurrentMessage("");
    setChatLoading(true);

    // 创建AI消息占位符
    const aiMessageId = "ai_" + Date.now();
    const aiMessage = {
      id: aiMessageId,
      type: "ai",
      content: "",
      timestamp: new Date(),
      isStreaming: true,
      service: chatService, // 记录使用的服务
    };

    setChatMessages((prev) => [...prev, aiMessage]);

    try {
      // 使用流式响应（现在支持自定义配置）
      await sendChatMessageStream(
        {
          message: messageToSend,
          conversation_id: conversationId,
          service: chatService, // 传入选择的服务
        },
        // onMessage: 处理每个流式数据块
        (streamData) => {
          setChatMessages((prev) =>
            prev.map((msg) =>
              msg.id === aiMessageId
                ? {
                    ...msg,
                    content: streamData.message || "",
                    chatId: streamData.chat_id,
                    conversationId: streamData.conversation_id,
                    timestamp: streamData.timestamp
                      ? new Date(streamData.timestamp * 1000)
                      : msg.timestamp,
                  }
                : msg
            )
          );
        },
        // onError: 处理错误
        (error) => {
          console.error("流式聊天失败:", error);

          // 显示错误提示
          message.error(error.message || "发送消息失败，请重试");

          // 更新AI消息为错误状态
          setChatMessages((prev) =>
            prev.map((msg) =>
              msg.id === aiMessageId
                ? {
                    ...msg,
                    content:
                      error.message ||
                      "抱歉，我暂时无法回复您的消息，请稍后再试。",
                    isStreaming: false,
                  }
                : msg
            )
          );
          setChatLoading(false);
        },
        // onComplete: 流式响应完成
        async (finalData) => {
          console.log("流式聊天完成:", finalData);

          // 更新消息状态
          setChatMessages((prev) =>
            prev.map((msg) =>
              msg.id === aiMessageId
                ? {
                    ...msg,
                    isStreaming: false,
                    chatId: finalData.chat_id,
                    conversationId: finalData.conversation_id,
                  }
                : msg
            )
          );

          setChatLoading(false);
        },
        // 可选的自定义配置
        {
          timeout: 300000, // 5分钟总超时
          idleTimeout: chatService === "gemini" ? 3000 : 30000, // Gemini使用3秒空闲超时，豆包和通义千问使用30秒
          serviceName:
            chatService === "gemini"
              ? "Gemini"
              : chatService === "doubao"
              ? "豆包"
              : "通义千问", // 服务名称用于日志
          errorMessage: "AI聊天服务暂时不可用，请稍后重试",
        }
      );
    } catch (error) {
      console.error("发送消息失败:", error);

      // 显示错误提示
      message.error(error.message || "发送消息失败，请重试");

      // 移除失败的AI消息或更新为错误状态
      setChatMessages((prev) =>
        prev.map((msg) =>
          msg.id === aiMessageId
            ? {
                ...msg,
                content:
                  error.message || "抱歉，我暂时无法回复您的消息，请稍后再试。",
                isStreaming: false,
              }
            : msg
        )
      );
      setChatLoading(false);
    }
  };

  // 处理Enter键发送消息
  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 如果正在检查token，显示加载状态
  if (isCheckingToken) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
          fontSize: "16px",
        }}>
        正在验证登录状态...
      </div>
    );
  }

  // 未登录且不是在登录页或注册页，强制跳转到登录页
  if (!hasToken && !isLoginPage && !isRegisterPage) {
    return <Navigate to="/login" replace />;
  }

  // 所有页面都使用 ConfigProvider 和主题配置
  return (
    <ConfigProvider
      theme={{
        algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
        token: {
          // 自定义主题色彩
          colorPrimary: "#1890ff",
          colorBgBase: isDarkMode ? "#141414" : "#ffffff",
          colorTextBase: isDarkMode ? "#ffffff" : "#000000",
        },
      }}
      modal={{
        contentBgColor: isDarkMode ? "#141414" : "#ffffff",
        titleColor: isDarkMode ? "#ffffff" : "#000000",
        colorBgMask: isDarkMode ? "rgba(0, 0, 0, 0.85)" : "rgba(0, 0, 0, 0.45)",
      }}
      message={{
        token: {
          colorBgDefault: isDarkMode ? "#262626" : "#ffffff",
          colorTextBase: isDarkMode ? "#ffffff" : "#000000",
          colorBorder: isDarkMode ? "#434343" : "#d9d9d9",
        },
      }}
      notification={{
        token: {
          colorBgDefault: isDarkMode ? "#262626" : "#ffffff",
          colorTextBase: isDarkMode ? "#ffffff" : "#000000",
          colorBorder: isDarkMode ? "#434343" : "#d9d9d9",
        },
      }}>
      <div
        style={{
          backgroundColor: isDarkMode ? "#141414" : "#ffffff",
          minHeight: "100vh",
          transition: "background-color 0.3s ease",
        }}>
        {/* 登录页面 */}
        {isLoginPage && <Login />}

        {/* 注册页面 */}
        {isRegisterPage && <Register />}

        {/* 主应用布局 - 只有已登录且不是登录/注册页面才显示 */}
        {!isLoginPage && !isRegisterPage && (
          <Layout
            style={{ minHeight: "100vh", backgroundColor: "transparent" }}>
            {/* 移动端菜单按钮 */}
            {isMobile && (
              <Button
                type="primary"
                icon={
                  siderCollapsed ? (
                    <span style={{ fontSize: 18 }}>☰</span>
                  ) : (
                    <span style={{ fontSize: 18 }}>✕</span>
                  )
                }
                onClick={() => setSiderCollapsed(!siderCollapsed)}
                style={{
                  position: "fixed",
                  left: 16,
                  top: 16,
                  zIndex: 1001,
                  width: 40,
                  height: 40,
                  padding: 0,
                  borderRadius: "50%",
                  boxShadow: isDarkMode
                    ? "0 2px 8px rgba(0,0,0,0.5)"
                    : "0 2px 8px rgba(0,0,0,0.15)",
                }}
              />
            )}

            {/* 遮罩层 - 移动端打开侧边栏时显示 */}
            {isMobile && !siderCollapsed && (
              <div
                onClick={() => setSiderCollapsed(true)}
                style={{
                  position: "fixed",
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  backgroundColor: "rgba(0, 0, 0, 0.5)",
                  zIndex: 999,
                  transition: "opacity 0.3s ease",
                }}
              />
            )}

            {/* 侧边栏 - 使用div代替Sider避免样式冲突 */}
            <div
              style={{
                width: isMobile ? 250 : siderWidth,
                background: isDarkMode ? "#1f1f1f" : "#fff",
                boxShadow: isDarkMode
                  ? "2px 0 8px rgba(0,0,0,0.3)"
                  : "2px 0 8px #f0f1f2",
                display: "flex",
                flexDirection: "column",
                position: "fixed",
                left: isMobile && siderCollapsed ? -250 : 0,
                top: 0,
                bottom: 0,
                zIndex: 1000,
                height: "100vh",
                maxHeight: "100vh", // 限制最大高度
                overflow: "hidden", // 隐藏溢出，让内部元素处理滚动
                transition: "all 0.3s ease",
              }}>
              {/* 顶部区域 - 退出按钮和个人中心在同一行 */}
              <div
                style={{
                  padding: isMobile ? 12 : 16,
                  flexShrink: 0, // 不允许收缩
                  minHeight: "auto", // 自动计算最小高度
                }}>
                {/* 深色模式切换 */}
                <div
                  style={{
                    marginBottom: 12,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                    padding: isMobile ? "6px 10px" : "8px 12px",
                    borderRadius: "6px",
                    backgroundColor: isDarkMode ? "#1f1f1f" : "#f5f5f5",
                    border: `1px solid ${isDarkMode ? "#434343" : "#d9d9d9"}`,
                  }}>
                  <Space size="small">
                    {isDarkMode ? (
                      <MoonOutlined style={{ color: "#1890ff" }} />
                    ) : (
                      <SunOutlined style={{ color: "#faad14" }} />
                    )}
                    <span
                      style={{
                        fontSize: isMobile ? "11px" : "12px",
                        color: isDarkMode ? "#fff" : "#666",
                      }}>
                      {isDarkMode ? "深色" : "浅色"}
                    </span>
                  </Space>
                  <Switch
                    size="small"
                    checked={isDarkMode}
                    onChange={toggleDarkMode}
                    checkedChildren={<MoonOutlined />}
                    unCheckedChildren={<SunOutlined />}
                  />
                </div>

                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: isMobile ? "6px" : "4px",
                    flexWrap: isMobile ? "wrap" : "nowrap",
                  }}>
                  {/* 退出登录按钮 - 缩短 */}
                  <Button
                    type="primary"
                    danger
                    onClick={() => {
                      handleLogout();
                      if (isMobile) setSiderCollapsed(true);
                    }}
                    size="small"
                    style={{
                      minWidth: isMobile ? "70px" : "60px",
                      flex: "0 0 auto",
                      fontSize: isMobile ? "12px" : "14px",
                    }}>
                    退出
                  </Button>

                  {/* 用户聊天按钮 */}
                  <div
                    onClick={() => {
                      navigate("/user-chat");
                      if (isMobile) setSiderCollapsed(true);
                    }}
                    style={{
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      width: "36px",
                      height: "28px",
                      borderRadius: "4px",
                      transition: "all 0.2s",
                      backgroundColor:
                        selectedKey === "/user-chat"
                          ? "#e6f7ff"
                          : isDarkMode
                          ? "#434343"
                          : "#f5f5f5",
                      border:
                        selectedKey === "/user-chat"
                          ? "1px solid #1890ff"
                          : `1px solid ${isDarkMode ? "#595959" : "#d9d9d9"}`,
                    }}
                    onMouseEnter={(e) => {
                      if (selectedKey !== "/user-chat") {
                        e.currentTarget.style.backgroundColor = isDarkMode
                          ? "#2a4d77"
                          : "#e6f7ff";
                        e.currentTarget.style.borderColor = "#40a9ff";
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (selectedKey !== "/user-chat") {
                        e.currentTarget.style.backgroundColor = isDarkMode
                          ? "#434343"
                          : "#f5f5f5";
                        e.currentTarget.style.borderColor = isDarkMode
                          ? "#595959"
                          : "#d9d9d9";
                      }
                    }}
                    title="用户聊天">
                    <TeamOutlined
                      style={{
                        fontSize: 14,
                        color:
                          selectedKey === "/user-chat"
                            ? "#1890ff"
                            : isDarkMode
                            ? "#fff"
                            : "#666",
                        transition: "color 0.2s",
                      }}
                    />
                  </div>

                  {/* AI聊天助手按钮 */}
                  <div
                    onClick={() => {
                      setChatVisible(true);
                      if (isMobile) setSiderCollapsed(true);
                    }}
                    style={{
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      width: "36px",
                      height: "28px",
                      borderRadius: "4px",
                      transition: "all 0.2s",
                      backgroundColor: chatVisible
                        ? "#e6f7ff"
                        : isDarkMode
                        ? "#434343"
                        : "#f5f5f5",
                      border: chatVisible
                        ? "1px solid #1890ff"
                        : `1px solid ${isDarkMode ? "#595959" : "#d9d9d9"}`,
                    }}
                    onMouseEnter={(e) => {
                      if (!chatVisible) {
                        e.currentTarget.style.backgroundColor = isDarkMode
                          ? "#2a4d77"
                          : "#e6f7ff";
                        e.currentTarget.style.borderColor = "#40a9ff";
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (!chatVisible) {
                        e.currentTarget.style.backgroundColor = isDarkMode
                          ? "#434343"
                          : "#f5f5f5";
                        e.currentTarget.style.borderColor = isDarkMode
                          ? "#595959"
                          : "#d9d9d9";
                      }
                    }}
                    title="AI聊天助手">
                    <RobotOutlined
                      style={{
                        fontSize: 14,
                        color: chatVisible
                          ? "#1890ff"
                          : isDarkMode
                          ? "#fff"
                          : "#666",
                        transition: "color 0.2s",
                      }}
                    />
                  </div>

                  {/* 个人中心头像 - 小按钮 */}
                  <div
                    onClick={() => {
                      navigate("/profile");
                      if (isMobile) setSiderCollapsed(true);
                    }}
                    style={{
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      width: "36px",
                      height: "28px",
                      borderRadius: "4px",
                      transition: "all 0.2s",
                      backgroundColor:
                        selectedKey === "/profile"
                          ? "#e6f7ff"
                          : isDarkMode
                          ? "#434343"
                          : "#f5f5f5",
                      border:
                        selectedKey === "/profile"
                          ? "1px solid #1890ff"
                          : `1px solid ${isDarkMode ? "#595959" : "#d9d9d9"}`,
                    }}
                    onMouseEnter={(e) => {
                      if (selectedKey !== "/profile") {
                        e.currentTarget.style.backgroundColor = isDarkMode
                          ? "#2a4d77"
                          : "#e6f7ff";
                        e.currentTarget.style.borderColor = "#40a9ff";
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (selectedKey !== "/profile") {
                        e.currentTarget.style.backgroundColor = isDarkMode
                          ? "#434343"
                          : "#f5f5f5";
                        e.currentTarget.style.borderColor = isDarkMode
                          ? "#595959"
                          : "#d9d9d9";
                      }
                    }}
                    title="个人中心">
                    {userImg ? (
                      <img
                        src={userImg}
                        alt="头像"
                        style={{
                          width: 20,
                          height: 20,
                          borderRadius: "50%",
                          objectFit: "cover",
                          background:
                            selectedKey === "/profile" ? "#1890ff" : "#666",
                          transition: "background-color 0.2s",
                        }}
                      />
                    ) : (
                      <Avatar
                        size={20}
                        icon={<UserOutlined />}
                        style={{
                          backgroundColor:
                            selectedKey === "/profile" ? "#1890ff" : "#666",
                          transition: "background-color 0.2s",
                        }}
                      />
                    )}
                  </div>
                </div>
              </div>

              {/* 菜单区域 - 占据剩余空间 */}
              <div
                style={{
                  flex: 1,
                  overflowY: "scroll", // 强制显示滚动条
                  overflowX: "hidden",
                  minHeight: 0, // 关键：允许flex子元素正确收缩
                  position: "relative", // 确保滚动容器定位正确
                  WebkitOverflowScrolling: "touch", // iOS 平滑滚动
                }}
                className={`menu-scroll-container ${
                  isDarkMode ? "dark-mode" : ""
                }`}>
                <Menu
                  mode="inline"
                  selectedKeys={
                    selectedKey !== "/profile" && selectedKey !== "/user-chat"
                      ? [selectedKey]
                      : []
                  }
                  style={{
                    borderRight: 0,
                    fontSize: isMobile ? 15 : siderWidth < 180 ? 14 : 16,
                    backgroundColor: "transparent",
                    // 移除高度限制，让内容自然扩展
                  }}
                  items={[
                    {
                      key: "main-group",
                      label: (
                        <Space size={8}>
                          <span>🌐 系统导航</span>
                        </Space>
                      ),
                      type: "group",
                      style: {
                        marginTop: "8px",
                        marginBottom: "4px",
                        fontSize: "12px",
                        color: isDarkMode ? "#8c8c8c" : "#8c8c8c",
                        fontWeight: "bold",
                        paddingLeft: "8px",
                      },
                    },
                    {
                      key: "/",
                      label: (
                        <Link
                          to="/"
                          onClick={() => isMobile && setSiderCollapsed(true)}>
                          <Space size={8}>
                            <HomeOutlined />
                            <span>首页</span>
                          </Space>
                        </Link>
                      ),
                      style: {
                        borderRadius: "8px",
                        margin: "4px 8px",
                      },
                    },
                    {
                      key: "/about",
                      label: (
                        <Link
                          to="/about"
                          onClick={() => isMobile && setSiderCollapsed(true)}>
                          <Space size={8}>
                            <InfoCircleOutlined />
                            <span>关于</span>
                          </Space>
                        </Link>
                      ),
                      style: {
                        borderRadius: "8px",
                        margin: "4px 8px",
                      },
                    },
                    // 只有admin用户才能看到管理相关菜单
                    ...(isAdmin()
                      ? [
                          {
                            key: "admin-group",
                            label: (
                              <Space size={8}>
                                <AppstoreOutlined />
                                <span>后台管理</span>
                              </Space>
                            ),
                            type: "group",
                            style: {
                              marginTop: "8px",
                              marginBottom: "4px",
                              fontSize: "12px",
                              color: isDarkMode ? "#8c8c8c" : "#8c8c8c",
                              fontWeight: "bold",
                              paddingLeft: "8px",
                            },
                          },
                          {
                            key: "/users",
                            label: (
                              <Link
                                to="/users"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <TeamOutlined />
                                  <span>用户管理</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                          {
                            key: "/articles",
                            label: (
                              <Link
                                to="/articles"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <FileTextOutlined />
                                  <span>文章管理</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                          {
                            key: "/category",
                            label: (
                              <Link
                                to="/category"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <TagsOutlined />
                                  <span>分类管理</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                          {
                            key: "/comments",
                            label: (
                              <Link
                                to="/comments"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <CommentOutlined />
                                  <span>评论管理</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                          {
                            key: "logs-group",
                            label: (
                              <Space size={8}>
                                <FileSearchOutlined />
                                <span>日志管理</span>
                              </Space>
                            ),
                            type: "group",
                            style: {
                              marginTop: "8px",
                              marginBottom: "4px",
                              fontSize: "12px",
                              color: isDarkMode ? "#8c8c8c" : "#8c8c8c",
                              fontWeight: "bold",
                              paddingLeft: "8px",
                            },
                          },
                          {
                            key: "/logs",
                            label: (
                              <Link
                                to="/logs"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <FileTextOutlined />
                                  <span>文章日志</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                          {
                            key: "/api-logs",
                            label: (
                              <Link
                                to="/api-logs"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <ApiOutlined />
                                  <span>API日志</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                        ]
                      : [
                          // 非admin用户显示文章浏览
                          {
                            key: "content-group",
                            label: (
                              <Space size={8}>
                                <span>📚 内容浏览</span>
                              </Space>
                            ),
                            type: "group",
                            style: {
                              marginTop: "8px",
                              marginBottom: "4px",
                              fontSize: "12px",
                              color: isDarkMode ? "#8c8c8c" : "#8c8c8c",
                              fontWeight: "bold",
                              paddingLeft: "8px",
                            },
                          },
                          {
                            key: "/articles",
                            label: (
                              <Link
                                to="/articles"
                                onClick={() =>
                                  isMobile && setSiderCollapsed(true)
                                }>
                                <Space size={8}>
                                  <FileTextOutlined />
                                  <span>文章浏览</span>
                                </Space>
                              </Link>
                            ),
                            style: {
                              borderRadius: "8px",
                              margin: "4px 8px",
                            },
                          },
                        ]),
                    // 统计分析：所有用户都可见
                    {
                      key: "analytics-group",
                      label: (
                        <Space size={8}>
                          <span>📊 分析工具</span>
                        </Space>
                      ),
                      type: "group",
                      style: {
                        marginTop: "8px",
                        marginBottom: "4px",
                        fontSize: "12px",
                        color: isDarkMode ? "#8c8c8c" : "#8c8c8c",
                        fontWeight: "bold",
                        paddingLeft: "8px",
                      },
                    },
                    {
                      key: "/stats",
                      label: (
                        <Link
                          to="/stats"
                          onClick={() => isMobile && setSiderCollapsed(true)}>
                          <Space size={8}>
                            <BarChartOutlined />
                            <span>统计分析</span>
                          </Space>
                        </Link>
                      ),
                      style: {
                        borderRadius: "8px",
                        margin: "4px 8px",
                      },
                    },
                  ]}
                />
              </div>
            </div>
            <Layout style={{ width: "100%", backgroundColor: "transparent" }}>
              <Content
                style={{
                  padding: isMobile
                    ? "80px 12px 16px 12px"
                    : window.innerWidth < 768
                    ? "16px 8px"
                    : window.innerWidth < 1200
                    ? "20px 12px"
                    : "20px 16px",
                  marginLeft: isMobile ? 0 : siderWidth,
                  minHeight: "100vh",
                  width: "auto",
                  maxWidth: "100vw",
                  overflow: "visible",
                  boxSizing: "border-box",
                  backgroundColor: "transparent",
                  transition: "margin-left 0.3s ease, padding 0.3s ease",
                }}>
                <div
                  style={{
                    width: "100%",
                    maxWidth: isMobile
                      ? "100%"
                      : window.innerWidth < 768
                      ? "100%"
                      : window.innerWidth < 1200
                      ? "900px"
                      : "1200px",
                    margin: "0 auto",
                    overflow: "visible",
                  }}>
                  <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/about" element={<About />} />
                    <Route path="/user-chat" element={<UserChat />} />
                    <Route path="/users" element={<Users />} />
                    <Route path="/articles" element={<Articles />} />
                    <Route path="/profile" element={<Profile />} />
                    <Route path="/article/:id" element={<ArticleDetail />} />
                    <Route path="/comments" element={<Comments />} />
                    <Route path="/logs" element={<Logs />} />
                    <Route path="/api-logs" element={<ApiLogs />} />
                    <Route path="/stats" element={<Stats />} />
                    <Route path="/category" element={<Category />} />
                    {/* 404 路由兜底 */}
                    <Route
                      path="*"
                      element={
                        <div
                          style={{
                            textAlign: "center",
                            marginTop: 100,
                            fontSize: 24,
                          }}>
                          404 Not Found
                        </div>
                      }
                    />
                  </Routes>
                </div>
              </Content>
            </Layout>

            {/* 聊天助手抽屉 */}
            <Drawer
              title={
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                  }}>
                  <Space>
                    <RobotOutlined style={{ color: "#1890ff" }} />
                    <span>聊天助手</span>
                  </Space>
                  <Space>
                    <Tooltip title="清除聊天记录">
                      <Button
                        type="text"
                        size="small"
                        icon={<ClearOutlined />}
                        onClick={handleClearChat}
                        disabled={chatMessages.length === 0}
                        style={{
                          color:
                            chatMessages.length === 0 ? undefined : "#ff4d4f",
                          borderColor: "transparent",
                        }}
                      />
                    </Tooltip>
                    <Tooltip title="切换AI服务">
                      <Select
                        value={chatService}
                        onChange={handleServiceChange}
                        size="small"
                        style={{ width: isMobile ? 90 : 100 }}
                        options={[
                          {
                            value: "gemini",
                            label: isMobile ? "Gem" : "Gemini",
                          },
                          { value: "doubao", label: "豆包" },
                          {
                            value: "tongyi",
                            label: isMobile ? "千问" : "通义千问",
                          },
                        ]}
                        suffixIcon={<SwapOutlined />}
                      />
                    </Tooltip>
                  </Space>
                </div>
              }
              placement="right"
              onClose={() => setChatVisible(false)}
              open={chatVisible}
              width={isMobile ? "100%" : 400}
              styles={{
                body: {
                  padding: 0,
                  display: "flex",
                  flexDirection: "column",
                  height: "100%",
                },
              }}>
              {/* 聊天消息区域 */}
              <div
                style={{
                  flex: 1,
                  overflow: "auto",
                  padding: isMobile ? "12px" : "16px",
                  backgroundColor: isDarkMode ? "#262626" : "#fafafa",
                  transition: "background-color 0.3s ease",
                }}>
                {isLoadingHistory ? (
                  <div
                    style={{
                      textAlign: "center",
                      color: isDarkMode ? "#888" : "#999",
                      padding: "40px 20px",
                    }}>
                    <Spin size="large" />
                    <div style={{ marginTop: 16 }}>正在加载历史记录...</div>
                  </div>
                ) : chatMessages.length === 0 ? (
                  <div
                    style={{
                      textAlign: "center",
                      color: isDarkMode ? "#888" : "#999",
                      padding: "40px 20px",
                    }}>
                    <RobotOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                    <div>您好！我是您的智能助手</div>
                    <div>
                      当前使用{" "}
                      <span style={{ color: "#1890ff", fontWeight: "bold" }}>
                        {chatService === "gemini"
                          ? "Gemini"
                          : chatService === "doubao"
                          ? "豆包"
                          : "通义千问"}
                      </span>{" "}
                      服务
                    </div>
                    <div>有什么可以帮助您的吗？</div>
                  </div>
                ) : (
                  <List
                    dataSource={chatMessages}
                    renderItem={(item) => (
                      <div
                        key={item.id}
                        style={{
                          marginBottom: 16,
                          display: "flex",
                          justifyContent:
                            item.type === "user" ? "flex-end" : "flex-start",
                        }}>
                        <div
                          style={{
                            maxWidth: item.type === "ai" ? "95%" : "80%", // 为代码内容提供更多空间
                            padding: "8px 12px",
                            borderRadius: "12px",
                            backgroundColor:
                              item.type === "user"
                                ? "#1890ff"
                                : isDarkMode
                                ? "#434343"
                                : "#fff",
                            color:
                              item.type === "user"
                                ? "#fff"
                                : isDarkMode
                                ? "#fff"
                                : "#333",
                            boxShadow: isDarkMode
                              ? "0 1px 2px rgba(0,0,0,0.3)"
                              : "0 1px 2px rgba(0,0,0,0.1)",
                            wordBreak: "break-word",
                            overflow: "hidden", // 防止代码块溢出
                            transition: "background-color 0.3s ease",
                          }}>
                          {item.type === "ai" ? (
                            <ChatMessage
                              content={item.content}
                              isStreaming={item.isStreaming}
                            />
                          ) : (
                            <div>{item.content}</div>
                          )}
                          <div
                            style={{
                              fontSize: "12px",
                              marginTop: "4px",
                              opacity: 0.7,
                              display: "flex",
                              alignItems: "center",
                              gap: "8px",
                            }}>
                            <span>{item.timestamp.toLocaleTimeString()}</span>
                            {item.type === "ai" && item.service && (
                              <span
                                style={{
                                  fontSize: "10px",
                                  padding: "1px 6px",
                                  borderRadius: "8px",
                                  backgroundColor:
                                    item.service === "gemini"
                                      ? "#4285f4"
                                      : item.service === "doubao"
                                      ? "#7c3aed"
                                      : "#ff6a00",
                                  color: "#fff",
                                  fontWeight: "bold",
                                }}>
                                {item.service === "gemini"
                                  ? "Gemini"
                                  : item.service === "doubao"
                                  ? "豆包"
                                  : "通义千问"}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    )}
                  />
                )}

                {/* 自动滚动锚点 */}
                <div ref={chatMessagesEndRef} />

                {/* 加载指示器 - 仅在连接建立前显示 */}
                {chatLoading &&
                  chatMessages.length > 0 &&
                  !chatMessages[chatMessages.length - 1]?.isStreaming && (
                    <div
                      style={{
                        display: "flex",
                        justifyContent: "flex-start",
                        marginBottom: 16,
                      }}>
                      <div
                        style={{
                          padding: "8px 12px",
                          borderRadius: "12px",
                          backgroundColor: isDarkMode ? "#434343" : "#fff",
                          boxShadow: isDarkMode
                            ? "0 1px 2px rgba(0,0,0,0.3)"
                            : "0 1px 2px rgba(0,0,0,0.1)",
                          transition: "background-color 0.3s ease",
                        }}>
                        <Spin size="small" />
                        <span style={{ marginLeft: 8, color: "#999" }}>
                          正在连接AI服务...
                        </span>
                      </div>
                    </div>
                  )}
              </div>

              {/* 输入区域 */}
              <div
                style={{
                  padding: isMobile ? "12px" : "16px",
                  borderTop: `1px solid ${isDarkMode ? "#434343" : "#f0f0f0"}`,
                  backgroundColor: isDarkMode ? "#1f1f1f" : "#fff",
                  transition: "all 0.3s ease",
                }}>
                <div style={{ display: "flex", gap: isMobile ? "6px" : "8px" }}>
                  <TextArea
                    value={currentMessage}
                    onChange={(e) => setCurrentMessage(e.target.value)}
                    onKeyPress={handleKeyPress}
                    placeholder="输入您的问题..."
                    autoSize={{ minRows: 1, maxRows: 4 }}
                    style={{ flex: 1 }}
                    disabled={chatLoading}
                  />
                  <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={handleSendMessage}
                    loading={chatLoading}
                    disabled={!currentMessage.trim()}
                  />
                </div>
                <div
                  style={{
                    fontSize: isMobile ? "11px" : "12px",
                    color: isDarkMode ? "#888" : "#999",
                    marginTop: isMobile ? "6px" : "8px",
                    transition: "color 0.3s ease",
                    lineHeight: 1.5,
                  }}>
                  {isMobile ? (
                    <>
                      <div>
                        当前：
                        <span style={{ color: "#1890ff", fontWeight: "bold" }}>
                          {chatService === "gemini"
                            ? "Gemini"
                            : chatService === "doubao"
                            ? "豆包"
                            : "通义千问"}
                        </span>
                      </div>
                      {chatLoading && (
                        <div style={{ color: "#1890ff" }}>
                          {chatMessages.some((msg) => msg.isStreaming)
                            ? "AI正在回复..."
                            : "正在连接..."}
                        </div>
                      )}
                    </>
                  ) : (
                    <>
                      按 Enter 发送，Shift + Enter 换行 • 当前使用：
                      <span style={{ color: "#1890ff", fontWeight: "bold" }}>
                        {chatService === "gemini"
                          ? "Gemini"
                          : chatService === "doubao"
                          ? "豆包"
                          : "通义千问"}
                      </span>{" "}
                      •
                      {chatLoading ? (
                        <span style={{ color: "#1890ff" }}>
                          {chatMessages.some((msg) => msg.isStreaming)
                            ? "AI正在实时回复中..."
                            : "正在连接AI服务..."}
                        </span>
                      ) : (
                        ""
                      )}
                    </>
                  )}
                </div>
              </div>
            </Drawer>
          </Layout>
        )}
      </div>
    </ConfigProvider>
  );
}
